<?php
class ControllerModuleNewsletter extends Controller {
	private $error = array();
	public $error_back = array();
	
	protected function index() {
		$this->language->load('module/newsletter'); 
				
      	$this->data['heading_title'] = $this->language->get('heading_title');
		$this->data['column_email'] = $this->language->get('column_email');
		$this->data['column_name'] = $this->language->get('column_name');
		$this->data['submit'] = $this->language->get('submit');

		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/newsletter.tpl')) {
			$this->template = $this->config->get('config_template') . '/template/module/newsletter.tpl';
		} else {
			$this->template = 'default/template/module/newsletter.tpl';
		}

		$this->render();
	}
	
	public function insert() {
		$this->language->load('module/newsletter'); 
		$this->load->model('catalog/newsletter');
		
		$this->data['text_success'] = $this->language->get('text_success');
				
		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_catalog_newsletter->addNewsletter($this->request->post);
			$this->error_back['success'] = $this->data['text_success'];
		}
		else {
			if(isset($this->error['warning'])) {
				$this->error_back['error']['warning'] = $this->error['warning'];
			}
			elseif(isset($this->error['email'])) {
				$this->error_back['error']['warning'] = $this->error['email'];
			}
			else
			{
				$this->error_back['error']['warning'] = $this->error['warning'];
			}
		}
		echo json_encode($this->error_back);
	}
	
	private function validateForm() {

		if ((utf8_strlen($this->request->post['email']) > 96) || (!preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->request->post['email']))) {
      		$this->error['email'] = $this->language->get('error_email');
    	}
		
		$newsletter_info = $this->model_catalog_newsletter->getNewsletterByEmail($this->request->post['email']);
		
		if (!isset($this->request->get['newsletter_id'])) {
			if ($newsletter_info) {
				$this->error['warning'] = $this->language->get('error_exists');
			}
		} else {
			if ($newsletter_info && ($this->request->get['newsletter_id'] != $newsletter_info['newsletter_id'])) {
				$this->error['warning'] = $this->language->get('error_exists');
			}
		}
				
		if (!$this->error) {
	  		return true;
		} else {
	  		return false;
		}
  	} 
}
?>